package com.situ.mall.controller;

import com.situ.mall.constant.RedisConstants;
import com.situ.mall.util.AliOSSUtil;
import com.situ.mall.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Controller
public class UploadController {
    @Autowired
    private RedisTemplate redisTemplate;

    //MultipartFile file封装了图片上传所有的信息
    @RequestMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile file) {
        //f7a9f3e6805a4e81b5d27245c6c30070
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // a.png
        String filename = file.getOriginalFilename();
        // .png
        String extension = filename.substring(filename.lastIndexOf("."));
        //f7a9f3e6805a4e81b5d27245c6c30070.png
        String newFilename = uuid + extension;
        //一、本地上传
        /*String filePath = "D:\\mypic\\" + newFilename;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }*/
        //二、阿里云oss上传
        String url = "";
        try {
            url = AliOSSUtil.uploadFile(newFilename, file.getInputStream());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //将所有上传的图片放到redis的set集合中
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE, url);

        return Result.ok("上传成功", url);
    }
}
